{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先我们创建一个数据库："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sqlite3\n",
    "# 创建数据库\n",
    "sqllite_path = 'llmdb.db'\n",
    "con = sqlite3.connect(sqllite_path)\n",
    "\n",
    "# 创建表\n",
    "sql = \"\"\"\n",
    "CREATE TABLE `section_stats` (\n",
    "  `部门` varchar(100) DEFAULT NULL,\n",
    "  `人数` int(11) DEFAULT NULL\n",
    ");\n",
    "\"\"\"\n",
    "c = con.cursor()\n",
    "cursor = c.execute(sql)\n",
    "c.close()\n",
    "con.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后给数据库填充一些数据："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "con = sqlite3.connect(sqllite_path)\n",
    "c = con.cursor()\n",
    "data = [\n",
    "    [\"专利部\",22],\n",
    "    [\"商标部\",25],\n",
    "]\n",
    "for item in data:\n",
    "    sql = \"\"\"\n",
    "    INSERT INTO section_stats (部门,人数) \n",
    "    values('%s','%d')\n",
    "    \"\"\"%(item[0],item[1])\n",
    "    c.execute(sql)\n",
    "    con.commit()\n",
    "c.close()\n",
    "con.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> ⚠️ 为了简化操作，本次使用智谱 AI 的 glm-4-flash、glm-4-plus 和 embedding-3 ，请自行申请：https://www.bigmodel.cn/invite?icode=tzUaambCl5Rc0B964McaGGczbXFgPRGIalpycrEwJ28%3D\n",
    "> 如使用本地大模型，请参考 tutorial/第06课-数据库对话Agent.md 。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"choices\":[{\"finish_reason\":\"stop\",\"index\":0,\"message\":{\"content\":\"法学专业的就业前景：挑战与机遇并存\\n\\n随着我国法治建设的不断推进，法学专业在高等教育中的地位日益凸显。法学专业毕业生在就业市场上具有广泛的需求，但同时面临着诸多挑战。本文将从法学专业的就业现状、就业前景以及应对策略三个方面进行论述。\\n\\n一、法学专业的就业现状\\n\\n1. 就业领域广泛\\n\\n法学专业毕业生可在政府机关、企事业单位、律师事务所、仲裁机构、法律援助机构等多个领域就业。其中，政府机关、企事业单位和律师事务所是法学专业毕业生的主要就业去向。\\n\\n2. 就业竞争激烈\\n\\n随着法学专业毕业生数量的逐年增加，就业竞争日益激烈。一方面，法学专业毕业生在求职过程中需要具备扎实的专业知识和实践经验；另一方面，用人单位对法学专业毕业生的综合素质要求越来越高。\\n\\n3. 就业地区差异明显\\n\\n法学专业毕业生在就业地区上存在明显差异。一线城市和发达地区的就业机会较多，薪资待遇较高；而二线及以下城市和欠发达地区的就业机会相对较少，薪资待遇较低。\\n\\n二、法学专业的就业前景\\n\\n1. 法治建设持续推进\\n\\n随着我国法治建设的不断推进，法律人才需求将持续增长。未来，法学专业毕业生在就业市场上将拥有更多的机会。\\n\\n2. 法律服务市场不断扩大\\n\\n随着市场经济的发展，法律服务市场不断扩大。企事业单位、个人对法律服务的需求日益增加，为法学专业毕业生提供了广阔的就业空间。\\n\\n3. 法律职业资格考试改革\\n\\n近年来，我国法律职业资格考试改革不断深化，考试难度和竞争激烈程度不断提高。通过法律职业资格考试的法学专业毕业生，将具备进入法律职业的资格，就业前景更加广阔。\\n\\n三、应对策略\\n\\n1. 提高自身综合素质\\n\\n法学专业毕业生应注重提高自身综合素质，包括专业知识、实践能力、沟通能力、团队协作能力等。通过参加实习、兼职、志愿服务等活动，积累实践经验，提升自身竞争力。\\n\\n2. 关注就业市场动态\\n\\n法学专业毕业生应关注就业市场动态，了解各行业、各地区的就业形势和需求。根据自身兴趣和特长，选择合适的就业方向。\\n\\n3. 培养跨学科知识\\n\\n法学专业毕业生应注重培养跨学科知识，如经济学、管理学、心理学等。这将有助于拓宽就业领域，提高就业竞争力。\\n\\n4. 拓展人际关系\\n\\n法学专业毕业生应积极参加各类社交活动，拓展人际关系。通过人脉资源，获取更多就业信息和机会。\\n\\n总之，法学专业在就业市场上具有广阔的前景。面对挑战，法学专业毕业生应不断提高自身综合素质，关注就业市场动态，培养跨学科知识，拓展人际关系，以应对激烈的就业竞争。在法治建设的背景下，法学专业毕业生将迎来更多的机遇，为我国法治事业贡献力量。\",\"role\":\"assistant\"}}],\"created\":1740363939,\"id\":\"20250224102523bd5dfee87bce476a\",\"model\":\"glm-4-flash\",\"request_id\":\"20250224102523bd5dfee87bce476a\",\"usage\":{\"completion_tokens\":551,\"prompt_tokens\":20,\"total_tokens\":571}}\n"
     ]
    }
   ],
   "source": [
    "# 我们先用requets库来测试一下大模型\n",
    "import json\n",
    "import requests\n",
    "BASE_URL = \"https://open.bigmodel.cn/api/paas/v4/chat/completions\"\n",
    "# 请替换为您的智谱AI API_KEY\n",
    "API_KEY = \"YOUR_API_KEY\"\n",
    "# 构建请求头\n",
    "headers = {\n",
    "    \"Authorization\": f\"Bearer {API_KEY}\",\n",
    "    \"Content-Type\": \"application/json\",\n",
    "    \"Accept\": \"application/json\"\n",
    "}\n",
    "payload = {\n",
    "  \"model\": \"glm-4-flash\",\n",
    "  \"messages\": [\n",
    "    {\n",
    "      \"role\": \"user\",\n",
    "      \"content\": \"请写一篇1000字左右的文章，论述法学专业的就业前景。\"\n",
    "    }\n",
    "  ]\n",
    "}\n",
    "response = requests.post(BASE_URL, json=payload, headers=headers)\n",
    "print(response.text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果想要流式输出，怎么办呢？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "法学专业的就业前景：挑战与机遇并存\n",
      "\n",
      "随着我国法治建设的不断深化，法学专业的重要性日益凸显。法学专业作为一门综合性学科，不仅涉及法律理论，还涵盖法律实践，培养具备法律素养、专业能力和创新精神的高级法律人才。然而，在当前就业市场竞争激烈的环境下，法学专业的就业前景既有挑战，也充满机遇。\n",
      "\n",
      "一、法学专业的就业挑战\n",
      "\n",
      "1. 市场竞争激烈\n",
      "\n",
      "近年来，法学专业毕业生人数逐年增加，导致就业市场竞争激烈。据统计，我国法学专业毕业生就业率一直处于较低水平。在求职过程中，法学专业毕业生需要面对众多竞争者，如其他专业毕业生、海外留学归国人员等。\n",
      "\n",
      "2. 就业岗位有限\n",
      "\n",
      "相较于其他热门专业，法学专业的就业岗位相对较少。一方面，我国法律职业资格考试（司法考试）通过率较低，导致从事法律职业的人数有限；另一方面，部分法学专业毕业生选择从事与法律无关的行业，进一步加剧了就业岗位的竞争。\n",
      "\n",
      "3. 就业地域差异明显\n",
      "\n",
      "法学专业毕业生在就业地域上存在明显差异。一线城市如北京、上海、广州等地，法学专业毕业生就业机会较多，薪资待遇相对较高；而二线、三线城市及农村地区，法学专业毕业生就业形势较为严峻。\n",
      "\n",
      "二、法学专业的就业机遇\n",
      "\n",
      "1. 法治建设需求旺盛\n",
      "\n",
      "随着我国法治建设的不断推进，法律人才需求持续增长。政府、企事业单位、律师事务所等机构对法学专业毕业生的需求量较大，为法学专业毕业生提供了广阔的就业空间。\n",
      "\n",
      "2. 法律服务行业蓬勃发展\n",
      "\n",
      "法律服务行业是我国经济发展的重要支撑。近年来，法律服务行业呈现出蓬勃发展的态势，如律师事务所、仲裁机构、法律援助机构等。这些机构为法学专业毕业生提供了丰富的就业机会。\n",
      "\n",
      "3. 法律职业教育市场潜力巨大\n",
      "\n",
      "随着社会对法律人才素质要求的提高，法律职业教育市场潜力巨大。法学专业毕业生可以从事法律教育培训、咨询、研究等工作，满足社会对法律人才的需求。\n",
      "\n",
      "4. 创业机会增多\n",
      "\n",
      "近年来，我国政府鼓励创新创业，为法学专业毕业生提供了更多创业机会。例如，成立律师事务所、法律咨询公司、法律服务平台等，为法学专业毕业生提供了实现自我价值、实现职业发展的平台。\n",
      "\n",
      "三、应对挑战，把握机遇\n",
      "\n",
      "1. 提高自身综合素质\n",
      "\n",
      "法学专业毕业生应注重提高自身综合素质，包括法律理论、实践能力、沟通能力、团队协作能力等。同时，关注行业动态，紧跟时代步伐，提高自己的竞争力。\n",
      "\n",
      "2. 拓宽就业渠道\n",
      "\n",
      "法学专业毕业生应拓宽就业渠道，不仅关注传统法律职业，还要关注新兴法律职业，如知识产权、互联网法律、环保法律等。此外，积极参加实习、兼职等活动，积累实践经验。\n",
      "\n",
      "3. 注重地域选择\n",
      "\n",
      "法学专业毕业生在就业地域上应注重选择，优先考虑一线城市及经济发展较快的地区。同时，关注农村地区、西部地区等就业市场，为我国法治建设贡献力量。\n",
      "\n",
      "4. 创新创业\n",
      "\n",
      "法学专业毕业生可以结合自身兴趣和市场需求，积极创新创业。在创业过程中，充分利用政府政策、社会资源，实现自我价值。\n",
      "\n",
      "总之，法学专业的就业前景既有挑战，也充满机遇。面对挑战，法学专业毕业生应不断提升自身综合素质，拓宽就业渠道，把握机遇，为实现自身职业发展奠定坚实基础。"
     ]
    }
   ],
   "source": [
    "# 我们先用requets库来测试一下大模型\n",
    "import json\n",
    "import requests\n",
    "BASE_URL = \"https://open.bigmodel.cn/api/paas/v4/chat/completions\"\n",
    "# 请替换为您的智谱AI API_KEY\n",
    "API_KEY = \"YOUR_API_KEY\"\n",
    "headers = {\n",
    "    \"Authorization\": f\"Bearer {API_KEY}\",\n",
    "    \"Content-Type\": \"application/json\",\n",
    "    \"Accept\": \"application/json\"\n",
    "}\n",
    "payload = {\n",
    "  \"model\": \"glm-4-flash\",\n",
    "  \"messages\": [\n",
    "    {\n",
    "      \"role\": \"user\",\n",
    "      \"content\": \"请写一篇1000字左右的文章，论述法学专业的就业前景。\"\n",
    "    }\n",
    "  ],\n",
    "  \"stream\": True\n",
    "}\n",
    "\n",
    "response = requests.post(BASE_URL, json=payload, headers=headers, stream=True)  # 在这里设置stream=True告诉requests不要立即下载响应内容  \n",
    "if response.status_code == 200:\n",
    "    buffer = b''  # 用字节串缓存数据\n",
    "    for chunk in response.iter_content():\n",
    "        if chunk:\n",
    "            buffer += chunk\n",
    "            while b'\\n\\n' in buffer:  # 检查是否有完整的数据包\n",
    "                # 分割数据包\n",
    "                package, buffer = buffer.split(b'\\n\\n', 1)\n",
    "                try:\n",
    "                    # 尝试解码完整的数据包\n",
    "                    package_str = package.decode('utf-8')\n",
    "                    if package_str.startswith('data: '):\n",
    "                        # 提取 JSON 部分\n",
    "                        json_str = package_str.replace('data: ', '').strip()\n",
    "                        data = json.loads(json_str)\n",
    "                        # 提取 content\n",
    "                        if data.get(\"choices\") and data[\"choices\"][0].get(\"delta\", {}).get(\"content\"):\n",
    "                            content = data[\"choices\"][0][\"delta\"][\"content\"]\n",
    "                            print(content, end='', flush=True)  # 直接打印内容，不加前缀，实时刷新\n",
    "                except (UnicodeDecodeError, json.JSONDecodeError):\n",
    "                    continue\n",
    "else:\n",
    "    print(f\"Error: {response.status_code}\")\n",
    "\n",
    "response.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple\n",
      "Requirement already satisfied: llama-index-llms-zhipuai in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (0.2.1)\n",
      "Collecting llama-index-embeddings-zhipuai\n",
      "  Downloading https://mirrors.aliyun.com/pypi/packages/6a/af/5b62fbc4256f00173b35e14bb406415f4202d2d323adda3991d9ba142ce2/llama_index_embeddings_zhipuai-0.2.0-py3-none-any.whl (2.9 kB)\n",
      "Requirement already satisfied: llama-index-core<0.13.0,>=0.12.0 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from llama-index-llms-zhipuai) (0.12.19)\n",
      "Requirement already satisfied: zhipuai<3.0.0.0,>=2.1.5.20230904 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-llms-zhipuai) (2.1.5.20250106)\n",
      "Requirement already satisfied: PyYAML>=6.0.1 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (6.0.2)\n",
      "Requirement already satisfied: SQLAlchemy>=1.4.49 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from SQLAlchemy[asyncio]>=1.4.49->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2.0.28)\n",
      "Requirement already satisfied: aiohttp<4.0.0,>=3.8.6 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.11.12)\n",
      "Requirement already satisfied: dataclasses-json in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.6.7)\n",
      "Requirement already satisfied: deprecated>=1.2.9.3 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.2.18)\n",
      "Requirement already satisfied: dirtyjson<2.0.0,>=1.0.8 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.0.8)\n",
      "Requirement already satisfied: filetype<2.0.0,>=1.2.0 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.2.0)\n",
      "Requirement already satisfied: fsspec>=2023.5.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2025.2.0)\n",
      "Requirement already satisfied: httpx in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.28.1)\n",
      "Requirement already satisfied: nest-asyncio<2.0.0,>=1.5.8 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.6.0)\n",
      "Requirement already satisfied: networkx>=3.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.4.2)\n",
      "Requirement already satisfied: nltk>3.8.1 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.9.1)\n",
      "Requirement already satisfied: numpy in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.26.4)\n",
      "Requirement already satisfied: pillow>=9.0.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (11.1.0)\n",
      "Requirement already satisfied: pydantic>=2.8.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2.10.6)\n",
      "Requirement already satisfied: requests>=2.31.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2.32.3)\n",
      "Requirement already satisfied: tenacity!=8.4.0,<10.0.0,>=8.2.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (8.3.0)\n",
      "Requirement already satisfied: tiktoken>=0.3.3 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.8.0)\n",
      "Requirement already satisfied: tqdm<5.0.0,>=4.66.1 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions>=4.5.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (4.12.2)\n",
      "Requirement already satisfied: typing-inspect>=0.8.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.9.0)\n",
      "Requirement already satisfied: wrapt in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.17.2)\n",
      "Requirement already satisfied: cachetools>=4.2.2 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from zhipuai<3.0.0.0,>=2.1.5.20230904->llama-index-llms-zhipuai) (5.5.1)\n",
      "Requirement already satisfied: pydantic-core>=2.14.6 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from zhipuai<3.0.0.0,>=2.1.5.20230904->llama-index-llms-zhipuai) (2.27.2)\n",
      "Requirement already satisfied: pyjwt<2.9.0,>=2.8.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from zhipuai<3.0.0.0,>=2.1.5.20230904->llama-index-llms-zhipuai) (2.8.0)\n",
      "Requirement already satisfied: aiohappyeyeballs>=2.3.0 in c:\\users\\huqi\\appdata\\roaming\\python\\python310\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2.4.6)\n",
      "Requirement already satisfied: aiosignal>=1.1.2 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.3.2)\n",
      "Requirement already satisfied: async-timeout<6.0,>=4.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (4.0.3)\n",
      "Requirement already satisfied: attrs>=17.3.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (25.1.0)\n",
      "Requirement already satisfied: frozenlist>=1.1.1 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.5.0)\n",
      "Requirement already satisfied: multidict<7.0,>=4.5 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (6.1.0)\n",
      "Requirement already satisfied: propcache>=0.2.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.2.1)\n",
      "Requirement already satisfied: yarl<2.0,>=1.17.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from aiohttp<4.0.0,>=3.8.6->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.18.3)\n",
      "Requirement already satisfied: anyio in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (4.8.0)\n",
      "Requirement already satisfied: certifi in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2025.1.31)\n",
      "Requirement already satisfied: httpcore==1.* in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.0.7)\n",
      "Requirement already satisfied: idna in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.10)\n",
      "Requirement already satisfied: h11<0.15,>=0.13 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from httpcore==1.*->httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.14.0)\n",
      "Requirement already satisfied: click in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from nltk>3.8.1->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (8.1.8)\n",
      "Requirement already satisfied: joblib in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from nltk>3.8.1->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.4.2)\n",
      "Requirement already satisfied: regex>=2021.8.3 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from nltk>3.8.1->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2024.11.6)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from pydantic>=2.8.0->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.7.0)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from requests>=2.31.0->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.4.1)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from requests>=2.31.0->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (2.3.0)\n",
      "Requirement already satisfied: greenlet!=0.4.17 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from SQLAlchemy>=1.4.49->SQLAlchemy[asyncio]>=1.4.49->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.1.1)\n",
      "Requirement already satisfied: colorama in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from tqdm<5.0.0,>=4.66.1->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (0.4.6)\n",
      "Requirement already satisfied: mypy-extensions>=0.3.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from typing-inspect>=0.8.0->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.0.0)\n",
      "Requirement already satisfied: marshmallow<4.0.0,>=3.18.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from dataclasses-json->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (3.26.1)\n",
      "Requirement already satisfied: packaging>=17.0 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from marshmallow<4.0.0,>=3.18.0->dataclasses-json->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (24.2)\n",
      "Requirement already satisfied: exceptiongroup>=1.0.2 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from anyio->httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.2.2)\n",
      "Requirement already satisfied: sniffio>=1.1 in c:\\programdata\\miniconda3\\envs\\dbgpt_env\\lib\\site-packages (from anyio->httpx->llama-index-core<0.13.0,>=0.12.0->llama-index-llms-zhipuai) (1.3.1)\n",
      "Installing collected packages: llama-index-embeddings-zhipuai\n",
      "Successfully installed llama-index-embeddings-zhipuai-0.2.0\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install llama-index-llms-zhipuai llama-index-embeddings-zhipuai -i https://mirrors.aliyun.com/pypi/simple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 配置对话模型\n",
    "from llama_index.llms.zhipuai import ZhipuAI\n",
    "\n",
    "llm = ZhipuAI(model=\"glm-4-plus\", api_key=\"YOUR API KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 配置Embedding模型\n",
    "from llama_index.embeddings.zhipuai import ZhipuAIEmbedding\n",
    "\n",
    "embedding = ZhipuAIEmbedding(model=\"embedding-3\", api_key=\"YOUR API KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是人工智能助手智谱清言（ChatGLM），是基于智谱 AI 公司于 2024 年训练的语言模型开发的。我的任务是针对用户的问题和要求提供适当的答复和支持。\n"
     ]
    }
   ],
   "source": [
    "# 测试对话模型\n",
    "response = llm.complete(\"你是谁？\")\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1024, list)"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 测试嵌入模型\n",
    "emb = embedding.get_text_embedding(\"你是谁？\")\n",
    "len(emb), type(emb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "输出 (1024, list)\n",
    "\n",
    "说明配置成功。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "导入Llama-index相关的库，并配置对话模型和嵌入模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.agent import ReActAgent  \n",
    "from llama_index.core.tools import FunctionTool  \n",
    "from llama_index.core import SimpleDirectoryReader, VectorStoreIndex, Settings  \n",
    "from llama_index.core.tools import QueryEngineTool   \n",
    "from llama_index.core import SQLDatabase  \n",
    "from llama_index.core.query_engine import NLSQLTableQueryEngine  \n",
    "from sqlalchemy import create_engine, select  \n",
    "\n",
    "\n",
    "# 配置默认大模型  \n",
    "Settings.llm = llm\n",
    "Settings.embed_model = embedding"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里的llm和embedding只要是llama-index支持的就行，有多种构建方法。详细可参见wow-rag课程的第二课。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 86,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建数据库查询引擎  \n",
    "engine = create_engine(\"sqlite:///llmdb.db\")  \n",
    "# prepare data  \n",
    "sql_database = SQLDatabase(engine, include_tables=[\"section_stats\"])  \n",
    "query_engine = NLSQLTableQueryEngine(  \n",
    "    sql_database=sql_database,   \n",
    "    tables=[\"section_stats\"],   \n",
    "    llm=Settings.llm  \n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建工具函数  \n",
    "def multiply(a: float, b: float) -> float:  \n",
    "    \"\"\"将两个数字相乘并返回乘积。\"\"\"  \n",
    "    return a * b  \n",
    "\n",
    "multiply_tool = FunctionTool.from_defaults(fn=multiply)  \n",
    "\n",
    "def add(a: float, b: float) -> float:  \n",
    "    \"\"\"将两个数字相加并返回它们的和。\"\"\"  \n",
    "    return a + b\n",
    "\n",
    "add_tool = FunctionTool.from_defaults(fn=add)\n",
    "\n",
    "# 把数据库查询引擎封装到工具函数对象中  \n",
    "staff_tool = QueryEngineTool.from_defaults(\n",
    "    query_engine,\n",
    "    name=\"section_staff\",\n",
    "    description=\"查询部门的人数。\"  \n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "> Running step e21793aa-2e53-43e6-82ba-1a567d26924a. Step input: 请从数据库表中获取`专利部`和`商标部`的人数，并将这两个部门的人数相加！\n",
      "\u001b[1;3;38;5;200mThought: The current language of the user is: Chinese. I need to use a tool to help me answer the question.\n",
      "Action: section_staff\n",
      "Action Input: {'input': '专利部'}\n",
      "\u001b[0m\u001b[1;3;34mObservation: 根据查询结果，专利部目前有22名员工。\n",
      "\u001b[0m> Running step 6ab94292-a8db-4ed5-816d-8d427ded8ba6. Step input: None\n",
      "\u001b[1;3;38;5;200mThought: I have the number of employees in the 专利部. Now I need to get the number of employees in the 商标部.\n",
      "Action: section_staff\n",
      "Action Input: {'input': '商标部'}\n",
      "\u001b[0m\u001b[1;3;34mObservation: 根据查询结果，商标部目前有25名员工。\n",
      "\u001b[0m> Running step 681c447c-1bee-4acd-98df-a0a832f4ca19. Step input: None\n",
      "\u001b[1;3;38;5;200mThought: I have the number of employees in both the 专利部 and 商标部. Now I need to add these two numbers.\n",
      "Action: add\n",
      "Action Input: {'a': 22, 'b': 25}\n",
      "\u001b[0m\u001b[1;3;34mObservation: 47\n",
      "\u001b[0m> Running step 728b4974-010d-437f-903f-0a58ef5f9880. Step input: None\n",
      "\u001b[1;3;38;5;200mThought: I can answer without using any more tools. I'll use the user's language to answer.\n",
      "Answer: 专利部和商标部的人数总和为47人。\n",
      "\u001b[0m"
     ]
    }
   ],
   "source": [
    "# 构建ReActAgent，可以加很多函数，在这里只加了加法函数和部门人数查询函数。\n",
    "agent = ReActAgent.from_tools([add_tool, staff_tool], verbose=True)  \n",
    "# 通过agent给出指令\n",
    "response = agent.chat(\"请从数据库表中获取`专利部`和`商标部`的人数，并将这两个部门的人数相加！\")  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "理想输出:\n",
    "```\n",
    "\n",
    "Thought: 首先我需要使用section_staff工具来获取“专利部”和“商标部”的人数。\n",
    "Action: section_staff\n",
    "Action Input: {'input': '专利部'}\n",
    "Observation: 根据查询结果，部门为“专利部”的统计数据共有22条。\n",
    "Thought: 我还需要获取“商标部”的人数，我将再次使用section_staff工具。\n",
    "Action: section_staff\n",
    "Action Input: {'input': '商标部'}\n",
    "Observation: 根据查询结果，部门为\"商标部\"的统计数据共有25条。\n",
    "Thought: 我现在有了两个部门的人数：“专利部”有22人，“商标部”有25人。下一步我需要将这两个数字相加。\n",
    "Action: add\n",
    "Action Input: {'a': 22, 'b': 25}\n",
    "Observation: 47\n",
    "Thought: 我可以回答这个问题了，两个部门的人数之和是47人。\n",
    "Answer: 专利部和商标部的总人数为47人。\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "专利部和商标部的人数总和为47人。\n"
     ]
    }
   ],
   "source": [
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "理想输出:\n",
    "专利部和商标部的人数总和为47人。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "注：目前这个功能不太稳定，上面这个结果看起来不错，但是是使用 glm-4-plus 才得到这个结果的。如果效果不好，需要换个更强的模型会更好。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "dbgpt_env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
